/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package l1j.server.server.utils;

import java.util.concurrent.ScheduledFuture;

import l1j.server.server.GeneralThreadPool;

public class Random {
	// 亂數表最大極限值
	private static final int _max = 0x3FF;

	// 目前的索引值
	private static int _idx = 0;

	// 亂數表主體
	private static double[] _randomTable = new double[_max + 1];

	// 亂數表更新間隔
	private static final int REFRESH_TABLE_INTERVAL = 10;

	// 自動更新任務實體
	private static ScheduledFuture<?> _scheduled;

	// 初始化
	public static void init() {
		// 初始化亂數表
		for (int i = 0; i < _max + 1; i++) {
			_randomTable[i] = (Math.random() + Math.random() + Math.random()) % 1.0D;
		}

		// 設定亂數表的自動更新
		if (_scheduled == null) {
			_scheduled = GeneralThreadPool.getInstance().scheduleAtFixedRate(
					new refreshTimer(), REFRESH_TABLE_INTERVAL,
					REFRESH_TABLE_INTERVAL);
		}
	}

	/** 取得機率(預設100%) **/
	public static boolean chance100(int chance) {
		return nextInt(100, 1) <= chance;
	}

	/** 取得機率(range分之chance) **/
	public static boolean chance(int chance, int range) {
		return nextInt(range, 1) <= chance;
	}

	// 取得整數
	public static int nextInt(int n) {
		return (int) (_randomTable[_idx++ & _max] * n);
	}

	// 取得整數+偏移
	public static int nextInt(int n, int offset) {
		return ((int) (_randomTable[_idx++ & _max] * n)) + offset;
	}

	// 隨機布林值
	public static boolean nextBoolean() {
		return ((int) (_randomTable[_idx++ & _max] * 2) == 1);
	}

	// 隨機位元
	public static byte nextByte() {
		return (byte) (_randomTable[_idx++ & _max] * 256);
	}

	// 隨機長整數
	public static long nextLong() {
		long l = (int) (_randomTable[_idx++ & _max] * Integer.MAX_VALUE);
		l = l << 32 + (int) (_randomTable[_idx++ & _max] * Integer.MAX_VALUE);
		return l;
	}

	// 亂數表自動更新用執行緒
	private static class refreshTimer implements Runnable {
		@Override
		public void run() {
			// 亂數決定要變更的表內容
			_randomTable[(int) (_randomTable[_idx++ & _max] * _max)] = (Math
					.random() + Math.random() + Math.random()) % 1.0D;
		}
	}
}